package cn.clq.ymcc.config;

import cn.clq.ymcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity//开启web授权
@EnableGlobalMethodSecurity(prePostEnabled=true)//开启方法授权
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IPermissionService permissionService;

    //指定一个密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    //授权规则配置，即访问某个资源需要什么权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        web授权只适用于单体项目，不适用于分布式项目
//        //使用web授权，将permission表中的数据交给security
//        //查询所有的权限
//        List<Permission> permissions = permissionService.selectList(null);
//        //设置权限规则
//        permissions.forEach(permission -> {
//            try {
//                http.authorizeRequests().antMatchers(permission.getResource()).hasAuthority(permission.getSn());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
        http.authorizeRequests()                                //授权配置
                .antMatchers("/login").permitAll()  //登录路径放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                .successForwardUrl("/login/loginSuccess")       // 设置登陆成功页
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查
    }
}